﻿//
// Copyright (c) 2011 David Díaz & Fran Pedreira
//
// This file is part of PlanSim.
//
// PlanSim is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PlanSim is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with PlanSim. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PlanSim.Core;
using System.Security.Permissions;
using Microsoft.Win32;


namespace PlanSim.Interfaz
{
    public partial class MDIParent : Form
    {
        /// <summary>
        /// Lista de simulaciones existentes en la aplicación.
        /// </summary>
        List<Configuracion> lSimulaciones = new List<Configuracion>();

        /// <summary>
        /// Lista de las cadenas que representan las rutas de los proyectos abiertos recientemente.
        /// </summary>
        List<string> lRecientes = new List<string>();

        public MDIParent()
        {
            InitializeComponent();
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            Configuracion configuracion = new Configuracion();
            lSimulaciones.Add(configuracion);

            FormWizard childForm = new FormWizard(configuracion);
            childForm.Tag = lSimulaciones.Count - 1;
            //childForm.MdiParent = this;
            
            /*configuracion.Procesos.Add(new Configuracion.Proceso("Word", 0, 25, "cero", Color.Blue));
            configuracion.Procesos.Add(new Configuracion.Proceso("Excel", 7, 15, "cero", Color.Green));
            configuracion.Procesos.Add(new Configuracion.Proceso("Access", 12, 21, "cero", Color.Magenta));
            configuracion.Procesos.Add(new Configuracion.Proceso("Outlook", 15, 21, "cero", Color.Orange));*/

            if (childForm.ShowDialog() == DialogResult.OK)
            {
                configuracion.GuardarEnFichero(@"c:kk.configuracion.xml");

				AbrirSimulacion(configuracion);
            }
        }

		private void AbrirSimulacion(Configuracion configuracion)
		{
			FormSimulacion simulacion = new FormSimulacion(configuracion);
			simulacion.MdiParent = this;
			simulacion.Show();
            actualizaRecientes();
		}

        private void OpenFile(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.InitialDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"Simulaciones");
            dialog.Filter = "Configuración|*.configuracion.xml";
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                AddRecientes(dialog.FileName);
				Configuracion configuracion = Configuracion.CargarDeFichero(dialog.FileName);
				AbrirSimulacion(configuracion);
            }
        }


        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Filter = "Archivos de texto (*.txt)|*.txt|Todos los archivos (*.*)|*.*";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog.FileName;
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void MDIParent_Load(object sender, EventArgs e)
        {
            CargarDelRegistro();
            actualizaRecientes(); 
        }

        private void actualizaRecientes()
        {
            tsRecientes.DropDownItems.Clear();
            int i = 0;
            foreach (string str in lRecientes)
            {
                System.Windows.Forms.ToolStripMenuItem tsMenuItem;
                tsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
                tsMenuItem.Text = "&" + i.ToString() + " " + acortaRuta(str);
                tsMenuItem.ToolTipText = str;
                tsMenuItem.Click += new System.EventHandler(this.ts_Click);
                tsRecientes.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { tsMenuItem });
                
                ++i;
            }

        }

        private string acortaRuta(string p)
        {
            
            if (p.Length < 55)
            {
                return(p);
            }
            else
            {
                string s;            
                char[] auxChar = { '\\' };
                s = p.Substring(p.Length - 50, 50);
                s = p.Substring(0, 3) + "...\\" + s.Split(auxChar, 2)[1];
                return(s);
            }
            
        }

        private void AddRecientes(string s)
        {

            for (int i = lRecientes.Count - 1; i >= 0; --i)
            {
                if (lRecientes.ElementAt(i) == s)
                {
                    lRecientes.RemoveAt(i);
                }
            }
            lRecientes.Insert(0,s);

        }

        private void CargarDelRegistro()
        {
            
            string subkey2 = @"Software\\Planificador";
            Microsoft.Win32.RegistryKey key;


            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subkey2);
            if (key == null)
            {
                key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subkey2);
            }

            foreach (string valueName in key.GetValueNames())
            {
                lRecientes.Add(key.GetValue(valueName).ToString());
            }

            key.Close();
            actualizaRecientes();
        }

        private void GuardarEnRegistro()
        {

            
            string subkey2 = @"Software\\Planificador";
            Microsoft.Win32.RegistryKey key;
            
            
            key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subkey2);
            if (key == null)
            {
                key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subkey2);
            }

            int i = 0;
            foreach (string str in lRecientes)
            {
                Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\\Software\\Planificador", (i).ToString(), str);
                ++i;
                if (i == 7) { break; }
             
            }

            key.Close();
            
        }


        private void MDIParent_FormClosing(object sender, FormClosingEventArgs e)
        {
            GuardarEnRegistro();
        }

        private void ts_Click(object sender, EventArgs e)
        {
            ToolStripItem ts;
            ts = (sender as ToolStripItem);
            AddRecientes(ts.ToolTipText);
            Configuracion configuracion = Configuracion.CargarDeFichero(ts.ToolTipText);
            AbrirSimulacion(configuracion);
        }

		private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			MostrarAcerca();
		}

		private void helpToolStripButton_Click(object sender, EventArgs e)
		{
			MostrarAcerca();
		}

		private void MostrarAcerca()
		{
			FormAcerca dialog = new FormAcerca();
			dialog.MdiParent = this;
			dialog.Show();
		}
    }
}
